#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: fu
"""

import Common

class Snake(object):
    def __init__(self):
        self.curdir = Common.pygame.K_RIGHT
        self.body = []
        self.colors = []
        self.length = 0
        
        for x in range(5):
            self.addnode()
            self.addcolor()
            self.length += 1
            
    def nextnode(self):
        left,top = (0,0)
        if self.body:
            left,top = (self.body[0].left,self.body[0].top)
            
        node = Common.pygame.Rect(left, top, 40, 40)
        if self.curdir == Common.pygame.K_LEFT:
            node.left -= 20
            node.top -= 10
        elif self.curdir == Common.pygame.K_RIGHT:
            node.left += 20
            node.top += 10
        elif self.curdir == Common.pygame.K_UP:
            node.left += 20
            node.top -= 10
        elif self.curdir == Common.pygame.K_DOWN:
            node.left -= 20
            node.top += 10
            
        return node
            
    # add node at 0
    def addnode(self):
        node = self.nextnode()
        self.body.insert(0, node)
        
    # delete node at -1
    def delnode(self, index = -1):
        self.body.pop(index)
        
    # add color at 0
    def addcolor(self):
        self.colors.insert(0, 'img/Blocks/' + Common.random_color() + ' 3' + '.png')
        
    def isdead(self, edges):
        # hits edge
        if (self.body[0].x, self.body[0].y) in edges:
            return True
        
        # hits itself
        if self.body[0] in self.body[1:]:
            return True
        
        return False
        
    def move(self):
        self.addnode()
        self.delnode()
        
    def changedirection(self, curkey):
        LR = [Common.pygame.K_LEFT, Common.pygame.K_RIGHT]
        UD = [Common.pygame.K_UP, Common.pygame.K_DOWN]
        if curkey in LR+UD:
            if not (((curkey in LR) and (self.curdir in LR)) or ((curkey in UD) and (self.curdir in UD))):
                self.curdir = curkey
                